package com.zhuhjay.common.core.socketio.handler;

import cn.hutool.core.util.StrUtil;
import com.corundumstudio.socketio.SocketIOClient;
import com.zhuhjay.common.base.annotation.ApiLimiter;
import com.zhuhjay.common.base.model.domain.LimiterDetail;
import com.zhuhjay.common.core.helper.ApiLimiterHelper;
import com.zhuhjay.common.netty.handler.SocketLimiterHandler;
import com.zhuhjay.common.security.context.LoginUserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author ZhuHJay
 * @date 2023/7/27 22:54
 */
@Slf4j
@Component
public class SocketLimiterHandlerImpl implements SocketLimiterHandler {

    @Resource
    private ApiLimiterHelper apiLimiterHelper;

    @Override
    public void handler(SocketIOClient client, String eventName, ApiLimiter apiLimiter) {
        // 这里的 ip 获取只会是微信服务器的 ip
        String ip = client.getHandshakeData().getAddress().getHostString();
        String username = LoginUserContext.getUsername();
        log.info("event:[{}], ip:[{}], user:[{}]", eventName, ip, username);
        apiLimiterHelper.limiter(eventName, LimiterDetail.of(username, apiLimiter),
                StrUtil.format("{} 事件过于频繁", eventName));
    }
}
